import { Context, Schema, h } from 'koishi';
import type { BiliAtAll } from './database';

declare module "koishi" {
  interface Tables {
    biliAtAll: BiliAtAll;
  }
};

export const name = 'bili-atall';

export const inject = ["database"];

export interface Config {
  listenBiliMsgAccList: string[];
  cooldownDurationMilliSecond: number;
  triggerKeyword: string;
  cooldownMessage: string;
  verboseConsoleOutput: boolean;
};

export const Config: Schema<Config> = Schema.intersect([
  Schema.object({
    listenBiliMsgAccList: Schema.array(String)
      .default([])
      .description("需要监听的B站账号列表，当这些账号发送包含关键词的消息时触发艾特全体。"),
    cooldownDurationMilliSecond: Schema.number()
      .default(60 * 60 * 1000) // 默认 1 小时冷却时间
      .description("艾特全体的冷却时间（毫秒）。"),
    triggerKeyword: Schema.string()
      .default("开播啦")
      .description("触发艾特全体的消息关键词。"),
    cooldownMessage: Schema.string()
      .default("艾特全体CD中")
      .description("在冷却期间发送的提示消息。"),
  }).description("艾特全体配置"),
  Schema.object({
    verboseConsoleOutput: Schema.boolean()
      .default(false)
      .description("是否在控制台输出详细信息，用于调试和开发。")
  }).description("调试配置")
])



export function apply(ctx: Context, config: Config) {

  ctx.model.extend('biliAtAll', {
		channelId: 'string',
		lastAtAll: 'integer',
		}, {
		primary: 'channelId',
	})

  if (!ctx.database) {
    ctx.logger.warn("数据库服务未加载，bili-at-all-notifier 插件将无法正常工作。");
    return;
  }

  ctx.on('message', async (session) => {

    // ctx.logger.info('qwqqwqqwq');
    
    if ( !config.listenBiliMsgAccList.includes(session.userId) ){
      if ( config.verboseConsoleOutput ){
        let msg = `用户 id:${session.userId}.不是监听的B站账号列表中的账号，跳过处理。`;
        ctx.logger.info(msg);
      }
      return;
    }

    if ( !session.content?.includes(config.triggerKeyword) ){
      if ( config.verboseConsoleOutput ){
        let msg = `用户 id:${session.userId} 的消息不包含关键词 "${config.triggerKeyword}"，跳过处理。`;
        ctx.logger.info(msg);
      }
      return;
    }

    if ( !session.channelId ){
      if ( config.verboseConsoleOutput ){
        let msg = `用户 id:${session.userId} 的消息没有 channelId，跳过处理。`;
        ctx.logger.info(msg);
      }
      return;
    }

    const channel_id = session.channelId;
    const now = Date.now();

    const records = await ctx.database
      .select('biliAtAll')
      .where( { channelId: channel_id } )
      .execute();
    
    const lastTime = records[0]?.lastAtAll ?? 0;

    if ( now - lastTime < config.cooldownDurationMilliSecond ){
      let cooldowmMsg = config.cooldownMessage;
      //todo: 加一点消息 还剩__时间
      await session.send(cooldowmMsg);
      return;
    }

    await ctx.database.upsert(
      'biliAtAll',
      [{
        channelId: channel_id,
        lastAtAll: Number(now),
      }]
    );

    await session.send(h.at("all"));

    if ( config.verboseConsoleOutput ) {
      ctx.logger.info(`用户 id:${session.userId} 在频道 ${channel_id} 发送了包含关键词 "${config.triggerKeyword}" 的消息，已触发艾特全体。`);
    }

  })
}
